<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}供应商`">
    <el-form
      ref="ruleFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="营业执照号码" prop="supplierLicense">
        <el-input v-model="drawerProps.row!.supplierLicense" placeholder="请填写供应商编号" clearable></el-input>
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input v-model="drawerProps.row!.supplierName" placeholder="请填写供应商名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="联系人姓名" prop="contactName">
        <el-input v-model="drawerProps.row!.contactName" placeholder="请填写联系人姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="联系人邮箱" prop="contactEmail">
        <el-input v-model="drawerProps.row!.contactEmail" placeholder="请填写联系人邮箱" clearable></el-input>
      </el-form-item>
      <el-form-item label="联系人电话" prop="contactPhone">
        <el-input v-model="drawerProps.row!.contactPhone" placeholder="请填写联系人电话" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="SupplierDrawer">
import { ref } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { Supplier } from "@/api/interface";
import axios from "axios";
import { defineEmits } from "vue";
const baseUrl = import.meta.env.VITE_BASE_URL;
const emit = defineEmits(["refresh"]);

const rules: FormRules = {
  supplierLicense: [{ required: true, message: "请输入营业执照编号?", trigger: "blur" }],
  supplierName: [{ required: true, message: "请输入供应商名称", trigger: "blur" }],
  contactName: [{ required: true, message: "请输入联系人姓名", trigger: "blur" }],
  contactEmail: [
    { required: true, message: "请输入联系人邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }
  ],
  contactPhone: [
    { required: true, message: "请输入联系人电话", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号格式?", trigger: "blur" }
  ]
};

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Supplier.ResSupplier>;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数?
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

function formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 提交数据
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      //静态数组新增数据
      if (drawerProps.value.title === "新增") {
        drawerProps.value.row.id = Date.now().toString();
        drawerProps.value.row.createTime = formatDate(new Date());
        const response = await axios.post(baseUrl + "/api/carbon/addSupplier", {
          supplierLicense: drawerProps.value.row.supplierLicense,
          supplierName: drawerProps.value.row.supplierName,
          contactName: drawerProps.value.row.contactName,
          contactEmail: drawerProps.value.row.contactEmail,
          contactPhone: drawerProps.value.row.contactPhone,
          createTime: drawerProps.value.row.createTime
        });
        if (response.data && response.data.code === 200) {
          ElMessage.success("新增供应商成功！");
          emit("refresh"); // 通知父组件刷新
        } else {
          ElMessage.error(response.data.msg || "新增供应商失败");
        }
      }
      //静态数组编辑数据
      else if (drawerProps.value.title === "编辑") {
        drawerProps.value.row.createTime = drawerProps.value.row.createTime || formatDate(new Date());
        const response = await axios.post(baseUrl + "/api/carbon/editSupplier", {
          id: drawerProps.value.row.id, // 编辑时需要传id
          supplierLicense: drawerProps.value.row.supplierLicense,
          supplierName: drawerProps.value.row.supplierName,
          contactName: drawerProps.value.row.contactName,
          contactEmail: drawerProps.value.row.contactEmail,
          contactPhone: drawerProps.value.row.contactPhone,
          createTime: drawerProps.value.row.createTime
        });
        if (response.data && response.data.code === 200) {
          ElMessage.success("编辑供应商成功！");
          emit("refresh"); // 通知父组件刷新
        } else {
          ElMessage.error(response.data.msg || "编辑供应商失败");
        }
      }
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
